package com.ruoyi.wifiauth.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.wifiauth.service.IWifiAuthService;
import com.ruoyi.wifiauth.domain.WifiAuthLog;
import com.ruoyi.common.redis.service.RedisService;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import com.ruoyi.wifiauth.api.AdvertisementClient;
import com.ruoyi.wifiauth.service.StrategyService;

@RestController
@RequestMapping("/auth")
public class WifiAuthController extends BaseController {

    @Autowired
    private IWifiAuthService wifiAuthService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private AdvertisementClient advertisementClient;
    
    @Autowired
    private StrategyService strategyService;

    @GetMapping("/ping")
    public AjaxResult ping() {
        return success("ok");
    }

    @PostMapping("/scan")
    public AjaxResult scan(@RequestParam("deviceId") String deviceId,
                           @RequestParam(value = "scene", required = false) String scene,
                           HttpServletRequest request) {
        String clientIp = request.getRemoteAddr();
        String limitKey = "wifi:scan:lim:" + deviceId + ":" + clientIp;
        if (Boolean.TRUE.equals(redisService.hasKey(limitKey))) {
            return error("请求过于频繁，请稍后重试");
        }
        redisService.setCacheObject(limitKey, 1, 3L, TimeUnit.SECONDS); // 3秒频控
        String sessionId = wifiAuthService.createAuthSession(deviceId, scene, clientIp);
        return success().put("sessionId", sessionId);
    }

    @PostMapping("/wechat/callback")
    public AjaxResult wechatCallback(@RequestParam("sessionId") String sessionId,
                                     @RequestParam("code") String code,
                                     @RequestParam("deviceId") String deviceId,
                                     @RequestBody(required = false) Map<String, Object> requestBody) {
        try {
            // TODO: 这里应该使用微信API通过code获取openId和unionId
            // 目前先模拟处理，实际项目中需要调用微信接口
            String openId = "mock_openid_" + System.currentTimeMillis();
            String unionId = null;
            
            boolean ok = wifiAuthService.recordWeChatAuth(sessionId, openId, unionId);
            return ok ? success() : error("会话不存在");
        } catch (Exception e) {
            logger.error("微信授权回调处理失败", e);
            return error("授权处理失败");
        }
    }

    @GetMapping("/status/{sessionId}")
    public AjaxResult status(@PathVariable String sessionId) {
        WifiAuthLog log = wifiAuthService.getStatus(sessionId);
        if (log == null) {
            return error("未找到会话");
        }
        return success(log);
    }

    /**
     * 获取设备广告策略
     */
    @GetMapping("/strategy/{deviceId}")
    public AjaxResult getStrategy(@PathVariable String deviceId) {
        return strategyService.getStrategyByDevice(deviceId);
    }
    
    /**
     * 清除设备策略缓存
     */
    @DeleteMapping("/strategy/cache/{deviceId}")
    public AjaxResult clearStrategyCache(@PathVariable String deviceId) {
        strategyService.clearStrategyCache(deviceId);
        return success("清除缓存成功");
    }
    
    /**
     * 清除所有策略缓存
     */
    @DeleteMapping("/strategy/cache")
    public AjaxResult clearAllStrategyCache() {
        strategyService.clearAllStrategyCache();
        return success("清除所有缓存成功");
    }
    
    /**
     * 预热策略缓存
     */
    @PostMapping("/strategy/warmup/{deviceId}")
    public AjaxResult warmupStrategyCache(@PathVariable String deviceId) {
        strategyService.warmupStrategyCache(deviceId);
        return success("预热缓存成功");
    }
} 